const express = require('express');
const fileUpload = require('express-fileupload');
const appConfig = require('../../build/compile-config');
const stringify = require('csv-stringify').stringify;
const bodyParser = require('body-parser');
const api = require('./apiList/index');
const path = require('path');
const choosePort = require('../../build/run/choose-port');
const history = require('connect-history-api-fallback');
const app = express();
const mockPort = appConfig.mockPort;
app.use(history());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.resolve(__dirname, 'static')));

var allowCors = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type,x-access-token');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
};

app.use(
    fileUpload({
        useTempFiles: true,
        tempFileDir: '/tmp/',
    }),
);

app.use(allowCors); //使用跨域中间件

const handleRequest = async (item, req, res) => {
    let { responseFn, status } = item;
    let params = req.body;
    let responseData = await responseFn(req.body, req, res);
    if (params && params.type === '404') {
        res.status(404).send({ data: '对不起404错误' });
    } else if (params.type === '500') {
        res.status(500).send({ data: '对不起500错误' });
    }
    res.status(status || 200).send(responseData);
};

const appRoute = () => {
    // post 方法处理函数
    Object.entries(api.postApi).forEach(([_path, item]) => {
        app.post(_path, (req, res) => {
            handleRequest(item, req, res);
        });
    });

    // get 方法处理函数
    Object.entries(api.getApi).forEach(([_path, item]) => {
        app.get(_path, (req, res) => {
            handleRequest(item, req, res);
        });
    });
};

app.get('/downloadFile', function (req, res) {
    let posts = require('./data/posts.json');
    res.setHeader('Content-Type', 'text/csv');
    res.setHeader('Content-Disposition', 'attachment; filename="' + 'download-' + Date.now() + '.csv"');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Pragma', 'no-cache');
    stringify(posts, { header: true }).pipe(res);
});

app.get('/', (req, res) => {
    res.send('hello, your mock server is working...');
});

app.post('/', (req, res) => {
    res.send('hello, this is a post request~~');
});

appRoute();

start();

async function start() {
    let newPort = await choosePort(mockPort, 'localhost');
    try {
        app.listen(newPort, () => {
            console.log(`Mock server is running at http://localhost:${newPort}`);
        });
    } catch (e) {
        console.log('服务启动报错' + e);
    }
}

//wget https://nodejs.org/dist/v16.14.2/node-v16.14.2-linux-x64.tar.xz && xz -d node-v16.14.2-linux-x64.tar.xz && tar -xvf node-v16.14.2-linux-x64.tar
/*
export NODE_HOME=/root/sofg/node-v16.14.2-linux-x64
export PATH=$PATH:$PATH:$NODE_HOME/bin
export NODE_PATH=$NODE_HOME/lib/node_modules
*/
